import { getRandom } from './util.js';
// 食物类
class Food {
    // 初始化
    constructor({x = 0, y = 0, width = 20, height = 20, color = 'green'} = {}){
        // 结构赋值 参数默认值
        // let options = {x = 0, y = 0, width = 20, height = 20, color = 'green'} || {};
        // 存储食物
        this.elements = [];
        // 坐标
        this.x = x;
        this.y = y;
 
        this.width = width;
        this.height = height;
        this.color = color;
    }
 
    render(map){
        this.remove(); // 删除之前创建的食物
 
        // 随机设置x,y的值
        this.x = getRandom(0, map.offsetWidth / this.width - 10) * this.width;
        this.y = getRandom(0, map.offsetHeight / this.height - 1) * this.height;
        console.log(this.x, this.y);
 
        // 创建食物 dom
        let div = document.createElement('div');
        map.appendChild(div);
        this.elements.push(div);
 
        // 设置div的样式
        div.style.position = 'absolute';
        div.style.left = this.x + 'px';
        div.style.top = this.y + 'px';
        div.style.width = this.width + 'px';
        div.style.height = this.height + 'px';
        div.style.backgroundColor = this.color;
    }
    remove() {
        // 从后往前
        for(let i = this.elements.length -1; i >= 0; i--){
            this.elements[i].parentNode.removeChild(this.elements[i]); // 删除div
            this.elements.splice(i, 1); // 删除数组中的元素
        }
    }
}
export default Food;